package com.kadron.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.intercept.BypassInterceptors;

import com.kadron.entity.Item;
import com.kadron.entity.ItemTypeMaterial;
import com.kadron.entity.Material;

@AutoCreate
@BypassInterceptors
@Name("itemTypeMaterialDAO")
public class KItemTypeMaterialDAO extends KDAO<ItemTypeMaterial> {

	private static final Log LOG = LogFactory.getLog(KItemTypeMaterialDAO.class);
	
	public ItemTypeMaterial find(long itId, long materialId) {
		EntityManager em = getEntityManager();
		try {
			return (ItemTypeMaterial) em.createQuery("SELECT e FROM ItemTypeMaterial e WHERE e.itemType.id = :it_id AND e.material.id = :material_id ")
			.setParameter("it_id", itId)
			.setParameter("material_id", materialId)
			.getSingleResult();			
		} catch (NoResultException e) {
			return null;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<ItemTypeMaterial> getItemTypeMaterial(long itId) {
		EntityManager em = getEntityManager();
		return em.createQuery("SELECT DISTINCT p FROM ItemTypeMaterial p WHERE " +
				"p.itemType.id = :it_id ")
		.setParameter("it_id", itId)
		.getResultList();
	}
	
	public Integer delete(long itId, List<Material> list) {
		if (list == null || list.isEmpty()) {
			if (LOG.isDebugEnabled()) {
				LOG.debug("CALL delete with empty list!");
			}
			return null;
		}
		EntityManager em = getEntityManager();
		Integer exec = null;
		try {
			 exec = em.createQuery("DELETE FROM ItemTypeMaterial WHERE itemType.id = :it_id AND material in (:list) ")
			.setParameter("it_id", itId)
			.setParameter("list", list)
			.executeUpdate();			
		} catch (HibernateException e) {
			if (LOG.isErrorEnabled()) {
				LOG.error("HibernateException on delete, "+e);
			}
		}
		return exec;
	}
	
	@SuppressWarnings("unchecked")
	public List<ItemTypeMaterial> getItemMaterials(long itemId) {
		EntityManager em = getEntityManager();
		return em.createQuery("SELECT DISTINCT p.material FROM ItemMaterial p WHERE p.item.id = :item_id ORDER BY p.ordinal")
				.setParameter("item_id", itemId)
				.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public List<ItemTypeMaterial> getAvailableItemMaterials(Item item) {
		EntityManager em = getEntityManager();
		return em.createQuery("SELECT DISTINCT e FROM ItemTypeMaterial e WHERE e.itemType.id=:it_id AND NOT EXISTS(SELECT 1 FROM ItemMaterial v WHERE v.material.id=e.id AND v.item.id=:item_id) ")
			.setParameter("item_id", item.getId())
			.setParameter("it_id", item.getItemType().getId())
			.getResultList();
	}
}
